<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="订单ID" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入订单ID" clearable filterable size="small"/>
      </el-form-item>
      <el-form-item label="品名" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择品名" clearable filterable size="small">
          <el-option
            v-for="dict in projectOptions"
            :key="dict.projectId"
            :label="dict.name"
            :value="dict.projectId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="请选择订单状态" clearable size="small">
          <el-option
            v-for="dict in orderStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期" prop="recordTime">
        <el-date-picker clearable size="small" style="width: 180px"
                        v-model="queryParams.recordTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择订单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:order:edit']"
        >修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          icon="el-icon-check"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleCheck"-->
      <!--          v-hasPermi="['product:order:check']"-->
      <!--        >审核-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          icon="el-icon-refresh-left"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleCancelCheck"-->
      <!--          v-hasPermi="['product:order:cancelCheck']"-->
      <!--        >取消审核-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:order:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单ID" align="center" prop="orderId" width="80"/>
      <el-table-column label="订单日期" sortable align="center" prop="recordTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品名" align="center" prop="projectCode" width="100"/>
      <el-table-column label="中文名称" align="center" prop="projectName"/>
      <el-table-column label="批号" align="center" prop="lotNumber" width="150"/>
      <!--      <el-table-column label="机型" align="center" prop="machineType" :formatter="machineTypeFormat"/>-->
      <!--      <el-table-column label="货号" align="center" prop="itemNo"/>-->
      <!--      <el-table-column label="包装规格" align="center" prop="spec"/>-->
      <!--      <el-table-column label="数量" align="center" prop="amount"/>-->
      <el-table-column label="配制日期" sortable align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="审核状态" align="center" prop="checkState" width="120">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag-->
      <!--            :type="scope.row.checkState === '1' ? 'success' : 'primary'"-->
      <!--            disable-transitions>{{ checkStateFormat(scope.row) }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="订单状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.orderState === '3' ? 'success':scope.row.orderState ==='2'? 'primary' : 'warning'"
            disable-transitions>{{ orderStateFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.checkState==='2'"
            @click="handleCheck(scope.row)"
            v-hasPermi="['product:order:check']"
          >审核
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-refresh-left"-->
          <!--            v-if="scope.row.checkState==='1'"-->
          <!--            @click="handleCancelCheck(scope.row)"-->
          <!--            v-hasPermi="['product:order:cancelCheck']"-->
          <!--          >取消审核-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-toilet-paper"
            @click="handleCreateCode(scope.row)"
            v-if="scope.row.checkState==='1'"
            v-hasPermi="['product:order:barCodePrint']"
          >生成标签
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleDetailShow(scope.row)"
            v-hasPermi="['product:order:detail']"
          >详细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:order:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:order:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试剂订单记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false">
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="15">
            <el-col :span="8">
              <el-form-item label="品名" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择品名"
                           filterable
                           :disabled="disabledProject"
                           @change="handleProjectChange(false)"
                >
                  <el-option
                    v-for="dict in projectOptions"
                    :key="dict.projectId"
                    :label="dict.name"
                    :value="dict.projectId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="中文名称" prop="projectName">
                <el-tooltip effect="light" :content="form.projectName" placement="top">
                  <el-input disabled v-model="form.projectName" placeholder="中文名称"/>
                </el-tooltip>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批号" prop="lotNumber">
                <el-input disabled v-model="form.lotNumber" placeholder="批号"/>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-for="(item2,index2) of reagentFormArr[0]" :key="index2">
              <el-form-item :label="item2.dictLabel+' 配制日期'">
                <el-date-picker style="width: 180px"
                                :clearable="false"
                                v-model="item2.preparationDate"
                                type="date"
                                @blur="handleReagentPreparationDateChange"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :picker-options="preparationDatePickerOptions"
                                placeholder="选择配制日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="配制日期" prop="createTime">
                <el-date-picker style="width: 180px"
                                v-model="form.createTime"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :picker-options="preparationDatePickerOptions"
                                @change="handleProjectChange(true,true)"
                                placeholder="选择配制日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="有效期" prop="expireDate">
                <el-date-picker disabled clearable style="width: 180px"
                                v-model="form.expireDate"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                placeholder="有效期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装日期" prop="requirePacTime">
                <el-date-picker clearable style="width: 180px"
                                v-model="form.requirePacTime"
                                format="yyyy-MM-dd"
                                type="date"
                                value-format="yyyy-MM-dd"
                                :picker-options="requireDatePickerOptions"
                                placeholder="选择包装日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!--            <transition-group name="el-fade-in">-->
            <!--              <div v-for="(item,index) of reagentFormRowCount" :key="index">-->
            <!--                <el-col :span="12" v-for="(item2,index2) of reagentFormArr[index]" :key="index2">-->
            <!--                  <el-form-item :label="item2.dictLabel+' 配制日期'">-->
            <!--                    <el-date-picker style="width: 180px"-->
            <!--                                    :clearable="false"-->
            <!--                                    v-model="item2.preparationDate"-->
            <!--                                    type="date"-->
            <!--                                    @blur="handleReagentPreparationDateChange"-->
            <!--                                    placeholder="选择配制日期">-->
            <!--                    </el-date-picker>-->
            <!--                  </el-form-item>-->
            <!--                </el-col>-->
            <!--              </div>-->
            <!--            </transition-group>-->
            <el-col :span="22">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" show-word-limit maxlength="255"
                          placeholder="请输入备注">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-divider><h4>生产计划</h4></el-divider>
            <el-col :span="8">
              <el-form-item label="机型">
                <el-select v-model="form.machineType" filterable clearable placeholder="请选择机型"
                           @change="handleMachineTypeChange"
                >
                  <el-option
                    v-for="dict in machineTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="货号" prop="amount">
                <el-select v-model="form.reagentFormId" filterable placeholder="请选择货号"
                           @change="handleItemNoChange"
                           value-key="reagentFormId"
                >
                  <el-option
                    v-for="item of itemNoOptions"
                    :key="item.reagentFormId"
                    :label="item.itemNo"
                    :value="item.reagentFormId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优先级" prop="amount">
                <el-input-number :min="1" v-model="form.priority" placeholder="请输入优先级"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="amount">
                <el-input-number :min="1" v-model="form.amount" placeholder="请输入数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button type="primary" @click="handleReagentAdd" v-show="!showUpdate">添 加</el-button>
                <el-button type="primary" @click="handleReagentUpdate" v-show="showUpdate">更 新</el-button>
              </el-form-item>
            </el-col>
            <el-table
              ref="multipleTable"
              :data="tableData"
              style="width: 100%"
              height="250"
              :default-sort="{prop: 'priority', order: 'descending'}"
              highlight-current-row
              @row-click="handleCurrentClick"
              @selection-change="handleSelectionChangeForm">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                label="机型"
                prop="machineType"
                :formatter="machineTypeFormat">
              </el-table-column>
              <el-table-column
                prop="itemNo"
                label="货号">
              </el-table-column>
              <el-table-column
                prop="reagentSpec"
                label="包装规格"
                show-overflow-tooltip
                width="250"
              >
              </el-table-column>
              <el-table-column
                label="数量"
                prop="amount">
              </el-table-column>
              <el-table-column
                label="优先级"
                sortable
                prop="priority">
                <template slot-scope="scope">
                  <el-tag
                    type="primary"
                    disable-transitions>{{ scope.row.priority }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click.stop="handleDeleteItem(scope.$index, scope.row)">删 除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleReagentItemBatchDel">批量删除</el-button>
        <el-button type="primary" @click="submitForm" :loading="loadingSubmit">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--根据机型生成标签-->
    <!-- 添加或修改试剂订单记录对话框 -->
    <el-dialog title="选择机型生成标签" :visible.sync="printOpen" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="printForm" :model="printForm" label-width="50px">
        <el-row :gutter="15">
          <el-table
            ref="multipleTable"
            :data="orderMachineList"
            style="width: 100%"
            height="350"
            @selection-change="handleSelectionChangePrintForm">
            <el-table-column
              type="selection"
              :selectable="selectable"
              width="55">
            </el-table-column>
            <el-table-column
              label="机型"
              prop="machineType"
              :formatter="machineTypeFormat">
            </el-table-column>
            <el-table-column
              prop="itemNo"
              label="货号">
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.state? 'success' : 'primary'">{{
                    scope.row.state ? '已生成标签' : '未生成标签'
                  }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createCode" :loading="loadingPrint">生成标签</el-button>
        <el-button @click="printCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {addOrder, addReagentCode, delOrder, exportOrder, getOrder, listOrder, updateOrder} from "@/api/product/order";
import {listProject, updateProject} from "@/api/product/project";
import {getReagentForm, listItemNoDetailByProjectAndMachineType} from "@/api/product/reagentForm";
import {addOrderList, delOrderListByOrderId, listOrderList} from "@/api/product/orderList";
import {addOrderListDetail, delOrderListDetailByOrderId} from "@/api/product/orderListDetail";
import {selectDictLabel} from "@/utils/ruoyi";
import {listBottleType} from "@/api/product/bottleType";

export default {
  name: "Order",
  data() {
    return {
      orderMachineList: [],
      printOpen: false,
      printForm: {},
      requireDatePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      preparationDatePickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      lastLotNo: undefined,
      defPriority: 1,
      errorCreateTime: false,
      errorFlag: false,
      disabledProject: false,
      orderListId: undefined,
      showUpdate: false,
      loadingSubmit: false,
      loadingPrint: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 试剂订单记录表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态字典
      checkStateOptions: [],
      // 订单状态字典
      orderStateOptions: [],
      // 机型字典
      machineTypeOptions: [],
      // 试剂类型字典
      reagentTypeOptions: [],
      //测试品名
      projectOptions: [],
      //效期汇总
      expireDateOptions: [],
      //货号汇总
      itemNoOptions: [],
      // 方法学字典
      testMethodOptions: [],
      allBottleTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: undefined,
        checkState: undefined,
        recordTime: undefined,
        orderState: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          {required: true, message: "品名不能为空", trigger: "change"}
        ],
        projectName: [
          {required: true, message: "中文名称不能为空", trigger: "change"}
        ],
        createTime: [
          {required: true, message: "配制日期不能为空", trigger: "change"}
        ],
        lotNumber: [
          {required: true, message: "批号不能为空", trigger: "change"}
        ],
        expireDate: [
          {required: true, message: "有效期不能为空", trigger: "change"}
        ],
        requirePacTime: [
          {required: true, message: "包装日期不能为空", trigger: "change"}
        ],
      },
      tableData: [],
      multipleSelection: [],
      multipleSelectionPrint: [],
    };
  },
  computed: {
    reagentTypeForm() {
      return this.reagentTypeOptions.slice()
    },
    reagentFormRowCount() {
      return Math.ceil(this.reagentTypeForm.length / 2)
    },
    reagentFormArr() {
      let arr = [];
      for (let i = 0; i < this.reagentTypeForm.length; i = i + 2) {
        arr.push(this.reagentTypeForm.slice(i, i + 2));
      }
      return arr;
    }
  },
  created() {
    this.getList();
    this.getDicts("reagent_check_state").then(response => {
      this.checkStateOptions = response.data;
    });
    this.getDicts("reagent_order_state").then(response => {
      this.orderStateOptions = response.data;
    });
    this.getDicts("machine_type").then(response => {
      this.machineTypeOptions = response.data;
    });
    this.getDicts("expiredate_list").then(response => {
      this.expireDateOptions = response.data;
    });
    this.getDicts("reagent_type_flag").then(response => {
      this.reagentTypeOptions = response.data;
    });
    this.getDicts("test_method").then(response => {
      this.testMethodOptions = response.data;
    });
    this.getProject()
    listBottleType().then(response => {
      this.allBottleTypeOptions = response.rows;
    });
  },
  methods: {
    getProject() {
      listProject(null).then(response => {
        this.projectOptions = response.rows;
      });
    },
    //单独的试剂类型配制日期改变触发
    handleReagentPreparationDateChange() {
      this.$forceUpdate();
      this.handleProjectChange(true)
    },
    //货号改变触发
    handleItemNoChange() {
      this.$forceUpdate();
      this.form.reagentForm = this.itemNoOptions.find(item => item.reagentFormId === this.form.reagentFormId)
      this.form.itemNo = this.form.reagentForm.itemNo
      if (this.form.itemNo) {
        let insReagentFormDetailList = this.form.reagentForm.insReagentFormDetailList;
        let arr = [];
        for (let reagentFormDetail of insReagentFormDetailList) {
          for (let reagentTypeOption of this.reagentTypeOptions) {
            if (reagentFormDetail.reagentType === reagentTypeOption.dictValue) {
              reagentTypeOption.preparationDate = this.form.createTime
              arr.push(reagentTypeOption);
            }
          }
        }
      }
    },
    //单行试剂信息删除
    handleDeleteItem(index, row) {
      this.tableData.splice(index, 1);
      this.form.reagentForm = undefined
      this.form.reagentFormId = undefined
      this.form.itemNo = undefined
      this.form.amount = 10
      this.defPriority > 1 ? this.defPriority -= 1 : this.defPriority = 1;
      this.form.priority = this.defPriority
      this.showUpdate = false
      this.orderListId = undefined
    },
    //处理试剂规格记录的批量删除
    handleReagentItemBatchDel() {
      if (this.multipleSelection.length === this.tableData.length) {
        this.tableData = []
      } else {
        for (let item of this.multipleSelection) {
          let findIndex = this.tableData.findIndex(row => row.itemNo === item.itemNo);
          this.tableData.splice(findIndex, 1)
        }
      }
      this.form.reagentForm = undefined
      this.form.reagentFormId = undefined
      this.form.itemNo = undefined
      this.form.amount = 10
      this.showUpdate = false
      this.orderListId = undefined
      this.defPriority = 1
      this.form.priority = this.defPriority
    },
    //添加需要下单的试剂
    handleReagentAdd() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (!this.form.machineType) {
            this.msgInfo('请选择机型');
            return
          }
          if (!this.form.reagentForm) {
            this.msgInfo('请选择货号')
            return
          }
          if (!this.form.amount) {
            this.msgInfo('请输入下单数量')
            return
          }
          if (!this.form.priority) {
            this.msgInfo('请输入优先级')
            return
          }
          let find = this.tableData.find(item => item.itemNo === this.form.itemNo && item.machineType === this.form.machineType);
          if (find) {
            this.$confirm('已添加过这个试剂，是否需要累加生产量？')
              .then(res => {
                find.amount += this.form.amount
                this.msgSuccess('已累加生产量为' + (find.amount));
              })
              .catch(err => {
                this.msgInfo('取消')
              })
          } else {
            let obj = {
              machineType: this.form.machineType,
              itemNo: this.form.itemNo,
              reagentSpec: '',
              amount: this.form.amount,
              priority: this.form.priority,
              reagentFormId: this.form.reagentForm.reagentFormId,
              insReagentFormDTO: this.form.reagentForm
            };
            this.form.reagentForm.insReagentFormDetailList.forEach(item => {
              if (item.bottleTypeId && item.reagentVolume && item.reagentSize) {
                let str = this.selectDictLabel(this.reagentTypeOptions, item.reagentType)
                  + ':' + item.reagentVolume + 'ml' + 'x'
                  + item.reagentSize + ' '
                obj.reagentSpec += str
              }
            })
            //构建需要创建的对象添加的表格中
            this.tableData.push(obj)
            this.defPriority += 1
            this.form.priority = this.defPriority;
          }
        }
      })
    },
    //已下单试剂信息更新
    handleReagentUpdate() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (!this.form.machineType) {
            this.msgInfo('请选择机型');
            return
          }
          if (!this.form.reagentForm) {
            this.msgInfo('请选择货号')
            return
          }
          if (!this.form.amount) {
            this.msgInfo('请输入下单数量')
            return
          }
          let find = this.tableData.find(item => item.orderListId === this.orderListId);
          if (find) {
            let obj = {
              orderListId: this.orderListId,
              machineType: this.form.machineType,
              itemNo: this.form.itemNo,
              reagentSpec: '',
              amount: this.form.amount,
              priority: this.form.priority,
              reagentFormId: this.form.reagentForm.reagentFormId,
              insReagentFormDTO: this.form.reagentForm
            };
            this.form.reagentForm.insReagentFormDetailList.forEach(item => {
              if (item.bottleTypeId && item.reagentVolume && item.reagentSize) {
                let str = this.selectDictLabel(this.reagentTypeOptions, item.reagentType)
                  + ':' + item.reagentVolume + 'ml' + 'x'
                  + item.reagentSize + ' '
                obj.reagentSpec += str
              }
            })
            //构建需要创建的对象添加的表格中
            let findIndex = this.tableData.findIndex(item => item.orderListId === this.orderListId);
            this.tableData.splice(findIndex, 1, obj)
          }
          this.msgSuccess('更新成功，请保存')
          this.form.reagentForm = undefined
          this.form.reagentFormId = undefined
          this.form.itemNo = undefined
          this.form.amount = 10
          this.form.priority = this.defPriority;
          this.showUpdate = false
        }
      })
    },
    //已下单试剂复选框选中触发
    handleSelectionChangeForm(val) {
      this.multipleSelection = val;
    },
    //复选框选中触发
    handleSelectionChangePrintForm(val) {
      this.multipleSelectionPrint = val;
    },
    //已下单试剂行单点击事件触发
    handleCurrentClick(item) {
      this.form.machineType = item.machineType;
      this.form.amount = item.amount;
      this.form.priority = item.priority;
      this.handleMachineTypeChange(item)
      this.showUpdate = true
      this.orderListId = item.orderListId
    },
    //机型改变时查询可以选择的货号
    handleMachineTypeChange(item) {
      this.form.itemNo = ''
      this.form.reagentForm = undefined
      this.form.reagentFormId = undefined
      if (this.form.projectId && this.form.machineType) {
        //根据品名、机型查询试剂表单中的货号供选择
        listItemNoDetailByProjectAndMachineType(
          {
            projectId: this.form.projectId,
            machineType: this.form.machineType
          }
        ).then(res => {
          this.itemNoOptions = res.data
          if (item && item instanceof Object) {
            this.form.itemNo = item.itemNo;
            this.form.reagentFormId = item.reagentFormId;
            getReagentForm(item.reagentFormId).then(res => {
              this.form.reagentForm = res.data
            });
          }
        })
      } else {
        this.itemNoOptions = []
      }
    },
    //项目改变时触发
    handleProjectChange(preparationDateChangeFlag, createTimeChange) {
      if (!this.disabledProject) {
        this.tableData = []
      }
      let project = this.projectOptions.find(one => one.projectId === this.form.projectId);
      this.errorCreateTime = false;
      if (project) {
        this.lastLotNo = project.lastLotNo
        this.form.projectName = project.nameDesc
        this.form.projectCode = project.name
        this.form.testMethod = selectDictLabel(this.testMethodOptions, project.testMethod)
        this.form.ceFlag = project.ceFlag
        this.form.registrationNo = project.registrationNo
        this.form.productionLicenseNo = project.productionLicenseNo
        let lastTime, minTime, mixFlag = false
        for (let item of this.reagentFormArr[0]) {
          if (!item.preparationDate || createTimeChange) {
            item.preparationDate = this.form.createTime;
          }
          let prepatationDate = new Date(item.preparationDate)
          if (!mixFlag && lastTime && prepatationDate.getTime() - lastTime.getTime() !== 0) {
            mixFlag = true
          }
          if (minTime) {
            if (prepatationDate.getTime() - minTime.getTime() < 0) {
              minTime = prepatationDate
            }
          } else {
            minTime = prepatationDate
          }
          lastTime = prepatationDate
          if (lastTime.getTime() - new Date().getTime() > 0 || lastTime.getTime() - new Date(this.form.requirePacTime).getTime() > 0) {
            this.msgError('配制日期不能大于当前时间或包装日期，请确认！')
            this.errorCreateTime = true;
          }
        }
        //根据产品自动生成批号和有效期
        minTime ? this.form.createTime = minTime : minTime = this.form.createTime;
        this.createExpireDate(project.effectivePeriod, minTime)
        this.createLotNumber(project, mixFlag, this.form.expireDate)
        if (!preparationDateChangeFlag) {
          this.handleMachineTypeChange()
        }
      } else {
        this.lastLotNo = undefined
      }
    },
    //生成有效期
    createExpireDate(effectivePeriod, time) {
      let date = new Date(time.getTime())
      date.setMonth(date.getMonth() + Number(effectivePeriod))
      date.setDate(date.getDate() - 1);
      this.form.expireDate = date
      this.form.expire = selectDictLabel(this.expireDateOptions, effectivePeriod)
    },
    //生成批号
    createLotNumber(project, mixFlag, expireDate) {
      //批号规则：产品简称+效期年最后一位+效期所在年的天数
      let year = expireDate.getFullYear().toString();
      let theLastDigitOfExpireDateYear = year.substring(year.length - 1);

      let currentYear = new Date(year);
      let date = new Date(expireDate.getTime())
      let hasDay = Math.ceil((date - currentYear) / 86400000) + 1
      let dayStr = hasDay < 10 ? ('00' + hasDay) : hasDay < 100 ? ('0' + hasDay) : hasDay
      this.form.lotNumber = project.shortName + theLastDigitOfExpireDateYear + dayStr;
      mixFlag ? this.form.lotNumber += '-1' : '';
      this.errorFlag = false;
      if (mixFlag && project.mflag) {
        this.msgError('混批和批号M标记同时存在，请确认！')
        this.errorFlag = true;
      } else if (project.mflag) {
        (project.mflag && (project.lastLotNo && project.lastLotNo === this.form.lotNumber)) || (project.mflag && !project.lastLotNo) ? this.form.lotNumber += 'M' : '';
      }
    },
    /** 查询试剂订单记录列表 */
    getList() {
      this.loading = true;
      this.getProject()
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询产品品名
    projectFormat(row, column) {
      let find = this.projectOptions.find(one => one.projectId === row.projectId);
      return find ? find.name : ''
    },
    // 审核状态字典翻译
    checkStateFormat(row, column) {
      return this.selectDictLabel(this.checkStateOptions, row.checkState);
    },
    // 订单状态字典翻译
    orderStateFormat(row, column) {
      return this.selectDictLabel(this.orderStateOptions, row.orderState);
    },
    // 机型字典翻译
    machineTypeFormat(row, column) {
      return this.selectDictLabel(this.machineTypeOptions, row.machineType);
    },
    //查询包装瓶名称
    bottleTypeFormat(row, column) {
      let find = this.allBottleTypeOptions.find(one => one.bottleTypeId === row.bottleTypeId);
      return find ? find.bottleName : ''
    },
    //查询包装瓶编号
    bottleTypeSerialNoFormat(row, column) {
      let find = this.allBottleTypeOptions.find(one => one.bottleTypeId === row.bottleTypeId);
      return find ? find.serialNo : ''
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    printCancel() {
      this.printOpen = false;
      this.printReset();
    },
    printReset() {
      this.resetForm("printForm");
      this.orderMachineList = [];
      this.loadingPrint = false;
    },
    // 表单重置
    reset() {
      let date = new Date()
      let date2 = this.parseTime(date, '{y}-{m}-{d}');
      this.defPriority = 1;
      this.form = {
        orderId: undefined,
        projectId: undefined,
        testMethod: undefined,
        ceFlag: undefined,
        registrationNo: undefined,
        productionLicenseNo: undefined,
        projectCode: undefined,
        projectName: undefined,
        createTime: date2,
        lotNumber: undefined,
        expire: undefined,
        expireDate: undefined,
        requirePacTime: date2,
        remark: undefined,
        orderUser: undefined,
        checkUser: undefined,
        checkState: undefined,
        checkTime: undefined,
        qa: undefined,
        recordTime: undefined,
        orderState: undefined,
        reagentForm: undefined,
        priority: this.defPriority,
        amount: 10
      };
      this.resetForm("form");
      this.tableData = []
      this.itemNoOptions = []
      this.orderListId = undefined
      this.showUpdate = false
      this.loadingSubmit = false
      this.reagentTypeOptions.filter(item => item.preparationDate = date2)
      this.lastLotNo = undefined
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.disabledProject = false
      this.title = "添加试剂订单记录";
    },
    /** 审核按钮操作*/
    handleCheck(row) {
      if (row.orderState !== '1') {
        this.msgInfo('该订单已完成审核');
        return
      }
      let username = this.$store.state.user.nickName;
      this.$confirm('审核后不能取消，请确认？')
        .then(res => {
          const orderId = row.orderId || this.ids
          let date = new Date();
          let date2 = this.parseTime(date);
          if (Array.isArray(orderId)) {
            if (orderId.length > 0) {
              new Promise(resolve => {
                resolve()
              }).then(res => {
                for (let id of orderId) {
                  updateOrder({
                    orderId: id,
                    checkState: 1,
                    orderState: 2,
                    checkTime: date2,
                    checkUser: username
                  })
                }
              }).then(res => {
                  this.msgSuccess('审核成功')
                  this.getList();
                }
              )
            }
          } else {
            updateOrder({
              orderId: orderId,
              checkState: 1,
              orderState: 2,
              checkTime: date2,
              checkUser: username
            }).then(response => {
              this.msgSuccess('审核成功')
              this.getList();
            });
          }
        })
        .catch(err => {
          this.msgInfo('取消')
        })
    },
    /** 取消审核按钮操作*/
    handleCancelCheck(row) {
      const orderId = row.orderId || this.ids
      if (Array.isArray(orderId)) {
        if (orderId.length > 0) {
          new Promise(resolve => {
            resolve()
          }).then(res => {
            for (let id of orderId) {
              updateOrder({
                orderId: id,
                checkState: 2,
                orderState: 1
              })
            }
          }).then(res => {
              this.msgSuccess('取消审核成功')
              this.getList();
            }
          )
        }
      } else {
        updateOrder({
          orderId: orderId,
          checkState: 2,
          orderState: 1
        }).then(response => {
          this.msgSuccess('取消审核成功')
          this.getList();
        });
      }
    },
    /**生成标签 包括盒贴和瓶贴*/
    handleCreateCode(row) {
      this.printOpen = true
      this.printForm = row;
      //通过OrderId查询需要生成标签的机型及状态
      listOrderList({orderId: row.orderId})
        .then(res => {
          this.orderMachineList = res.rows;
        })
    },
    createCode() {
      if (this.multipleSelectionPrint.length <= 0) {
        this.msgInfo('没有选择需要生成标签的内容')
        return
      }
      this.loadingPrint = true;
      this.printForm.reagentOrderLists = this.multipleSelectionPrint;
      addReagentCode(this.printForm)
        .then(res => {
          this.msgSuccess('需要打印的标签记录已生成！')
          //通过OrderId查询需要生成标签的机型及状态
          listOrderList({orderId: this.printForm.orderId})
            .then(res => {
              this.orderMachineList = res.rows;
              this.loadingPrint = false;
            })
        })
    },
    selectable(row, index) {
      return !row.state
    },
    /** 查看订单详细*/
    handleDetailShow(row) {
      this.$router.push({path: "/product/order/detail", query: {orderId: row.orderId}})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.orderState === '2') {
        this.msgInfo('该订单已审核不能修改')
        return
      }
      if (row.orderState === '3') {
        this.msgInfo('该订单已完成不能修改')
        return
      }
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.tableData = this.form.reagentOrderLists;
        this.open = true;
        this.disabledProject = true
        this.title = "修改试剂订单记录";
        for (let rf of this.reagentFormArr[0]) {
          for (let row of this.tableData[0].reagentOrderListDetails) {
            if (rf.dictValue === row.reagentType) {
              rf.preparationDate = new Date(row.createTime)
              break
            }
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.tableData.length <= 0) {
            this.msgInfo('请添加计划生产的试剂')
            return
          }
          if (this.errorFlag) {
            this.msgError('混批和批号M标记同时存在，请确认！')
            return
          }
          if (this.errorCreateTime) {
            this.msgError('配制日期不能大于当前时间或包装日期，请确认！')
            return
          }
          if (this.form.orderId != undefined) {
            new Promise(resolve => {
              resolve()
            }).then(async res => {
              this.loadingSubmit = true
              let orderId = this.form.orderId;
              this.form.orderUser = this.$store.state.user.nickName
              await updateOrder(this.form)
              await delOrderListByOrderId(orderId)
              await delOrderListDetailByOrderId(orderId)
              this.makeExpireDateAndLotNo()
              for (let item of this.tableData) {
                let orderList = item
                orderList.orderId = orderId
                await addOrderList(orderList).then(async response => {
                  if (response.code === 200) {
                    let orderListId = response.data.orderListId;
                    for (let reagentForm of item.insReagentFormDTO.insReagentFormDetailList) {
                      let find = this.reagentFormArr[0].find(rf => rf.dictValue === reagentForm.reagentType);
                      //根据规格计算需要生产的具体试剂类型数量
                      let orderListDetail = {
                        reagentType: reagentForm.reagentType,
                        amount: item.amount * reagentForm.reagentSize,
                        priority: item.priority,
                        reagentVolume: reagentForm.reagentVolume,
                        productVolume: reagentForm.productVolume,
                        bottleType: this.bottleTypeFormat(reagentForm),
                        bottleTypeSerialNo: this.bottleTypeSerialNoFormat(reagentForm),
                        orderListId: orderListId,
                        orderId: orderId,
                        reagentFormId: reagentForm.reagentFormId,
                        machineType: orderList.machineType,
                        createTime: find ? find.preparationDate : this.form.createTime,
                        expireDate: find ? find.expireDate : this.form.expireDate,
                        lotNo: find ? find.lotNo : this.form.lotNumber
                      }
                      await addOrderListDetail(orderListDetail)
                    }
                  }
                })
              }
              this.updateMflag();
            }).then(res => {
              this.msgSuccess("修改成功");
              this.loadingSubmit = false
              this.open = false;
              this.getList();
            })
          } else {
            new Promise(resolve => {
              resolve()
            }).then(async res => {
              this.loadingSubmit = true
              this.form.orderUser = this.$store.state.user.nickName
              await addOrder(this.form).then(async response => {
                if (response.code === 200) {
                  let orderId = response.data.orderId
                  this.makeExpireDateAndLotNo()
                  for (let item of this.tableData) {
                    let orderList = item
                    orderList.orderId = orderId
                    await addOrderList(orderList).then(async response => {
                      if (response.code === 200) {
                        let orderListId = response.data.orderListId;
                        for (let reagentForm of item.insReagentFormDTO.insReagentFormDetailList) {
                          let find = this.reagentFormArr[0].find(rf => rf.dictValue === reagentForm.reagentType);
                          //根据规格计算需要生产的具体试剂类型数量
                          let orderListDetail = {
                            reagentType: reagentForm.reagentType,
                            amount: item.amount * reagentForm.reagentSize,
                            priority: item.priority,
                            reagentVolume: reagentForm.reagentVolume,
                            productVolume: reagentForm.productVolume,
                            bottleType: this.bottleTypeFormat(reagentForm),
                            bottleTypeSerialNo: this.bottleTypeSerialNoFormat(reagentForm),
                            orderListId: orderListId,
                            orderId: item.orderId,
                            reagentFormId: reagentForm.reagentFormId,
                            machineType: orderList.machineType,
                            createTime: find ? find.preparationDate : this.form.createTime,
                            expireDate: find ? find.expireDate : this.form.expireDate,
                            lotNo: find ? find.lotNo : this.form.lotNumber
                          }
                          await addOrderListDetail(orderListDetail)
                        }
                      }
                    })

                  }
                }
              });
              this.updateMflag();
            }).then(res => {
              this.msgSuccess("新增成功");
              this.loadingSubmit = false
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    updateMflag() {
      let mflag = this.lastLotNo && this.lastLotNo !== this.form.lotNumber
      if (mflag) {
        updateProject({
          projectId: this.form.projectId,
          lastLotNo: this.form.lotNumber,
          mflag: false
        });
      }
    },
    makeExpireDateAndLotNo() {
      let project = this.projectOptions.find(item => item.projectId === this.form.projectId);
      for (let reagentFormOne of this.reagentFormArr[0]) {
        //配制日期
        let preparationDate = new Date(reagentFormOne.preparationDate);
        //计算效期
        let expireDate = this.getExpireDate(project.effectivePeriod, preparationDate);
        //计算批号
        let lotNo = this.getLotNo(project, expireDate);
        reagentFormOne.expireDate = expireDate
        reagentFormOne.lotNo = lotNo
      }
    },
    //计算瓶贴效期
    getExpireDate(effectivePeriod, date) {
      date.setMonth(date.getMonth() + Number(effectivePeriod))
      date.setDate(date.getDate() - 1);
      return date
    },
    //计算瓶贴批号
    getLotNo(project, expireDate) {
      //批号规则：产品简称+效期年最后一位+效期所在年的天数
      let year = expireDate.getFullYear().toString();
      let theLastDigitOfExpireDateYear = year.substring(year.length - 1);

      let currentYear = new Date(year);
      let date = new Date(expireDate.getTime())
      let hasDay = Math.ceil((date - currentYear) / 86400000) + 1
      let dayStr = hasDay < 10 ? ('00' + hasDay) : hasDay < 100 ? ('0' + hasDay) : hasDay
      let lotNo = project.shortName + theLastDigitOfExpireDateYear + dayStr
      if (project.mflag) {
        project.mflag ? lotNo += 'M' : '';
      }
      return lotNo;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$confirm('是否确认删除试剂订单记录的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async function () {
        await delOrder(orderIds);
        if (Array.isArray(orderIds)) {
          for (let orderId of orderIds) {
            await delOrderListByOrderId(orderId)
            await delOrderListDetailByOrderId(orderId)
          }
        } else {
          await delOrderListByOrderId(orderIds)
          await delOrderListDetailByOrderId(orderIds)
        }
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function (err) {
        console.log(err)
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有试剂订单记录数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportOrder(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    }
  }
};
</script>
